package com.imooc.bilibili.handler;

import com.imooc.bilibili.domain.core.JsonResponse;
import com.imooc.bilibili.exception.ConditionException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author gcq
 * @Create 2022-05-23
 */
// 全局异常处理
@RestControllerAdvice
// 优先级最高
@Order(value = Ordered.LOWEST_PRECEDENCE)
public class CommonGlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    public JsonResponse<String> commonExceptionHandler(HttpServletRequest request, Exception exception) {
        String errorMsg = exception.getMessage();
        if(exception instanceof ConditionException) {
            // 匹配的是条件异常，单独处理
            String errorCode = ((ConditionException) exception).getCode();
            return new JsonResponse<>(errorCode, errorMsg);
        } else {
            return new JsonResponse<>("500", errorMsg);
        }
    }

}